package com.lvmama.rhino.web;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.lvmama.rhino.base.BaseControllerSupport;
import com.lvmama.rhino.base.TreeNodeViewUtil;
import com.lvmama.rhino.entity.CommonStatisticsSqlVO;
import com.lvmama.rhino.pojo.CodeNode;
import com.lvmama.rhino.pojo.CommonStatisticsResult;
import com.lvmama.rhino.pojo.TreeNodeView;
import com.lvmama.rhino.service.TreeStatisticsService;

@Controller
@RequestMapping("treeStatistics")
public class TreeStatisticsController extends BaseControllerSupport{
    
    @Autowired
    private TreeStatisticsService messageService;
    
    @RequestMapping("FlowStatisticsTree")
	public String landPageFlow(ModelMap model){
    	//设置页面的默认时间,今天和七天前
    	Calendar calendar = Calendar.getInstance();
    	calendar.setTime(new Date());
    	calendar.add(Calendar.DAY_OF_MONTH, -7);
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	String begin = sdf.format(calendar.getTime());
    	
    	Calendar calendarEnd = Calendar.getInstance();
    	calendarEnd.setTime(new Date());
    	calendarEnd.add(Calendar.DAY_OF_MONTH, -1);
    	String end = sdf.format(calendarEnd.getTime());
    	
    	model.addAttribute("beginDate", begin);
    	model.addAttribute("endDate", end);
		return "application/tree/FlowStatisticsTree";
	}
    
    /**
     * 
    * @Title: QueryTreeStructureFlow 
    * @Description: 初始化树的结构
    * @param @param rootNodeId,beginDate,endDate
    * @return TreeNodeView    返回类型 
    * @throws
     */
    @RequestMapping("QueryTreeStructureFlow")
    @ResponseBody
    public Map QueryTreeStructureFlow(@RequestParam("rootNodeId") String rootNodeId,@RequestParam("beginDate") String beginDate,@RequestParam("endDate") String endDate){
    	//校验时间规则：1查询3年前的数据，2开始和结束跨度为3个月
    	Map returnMap = new HashMap();
    	String mess = TreeNodeViewUtil.checkDate(beginDate, endDate);
    	if(mess.length()>0){
    		returnMap.put("mess", mess);
    		return returnMap;
    	}
    	
    	//刷新code码及树节点
    	List<CodeNode> codeList = messageService.QueryAllCodeNode();
    	TreeNodeViewUtil.refreshCodeList(codeList);
    	List<TreeNodeView> nodeList = messageService.QueryAllTreeNodeView();
    	TreeNodeViewUtil.refreshNodeList(nodeList);
    	
    	//获取根节点，初始化子节点
    	TreeNodeView root = TreeNodeViewUtil.getRootTreeNode(rootNodeId);
    	//TreeNodeViewUtil.initRootChildrenNode(root);
    	
    	TreeNodeViewUtil.initRootChildrenNodeList(root);
    	
    	//根据属性的值域，进行节点的显示名称映射，节点的nodeDesc设置
    	//现在是每个节点都映射，其实应该根据root的哪棵树和属性集是否需要映射，来一起判断，决定是否进行映射
    	for(TreeNodeView tn : nodeList){//根据属性值，映射所有的属性信息
    		String sttr = tn.getAttributeSet();
    		String str = "";
    		if(null != tn.getAttributeValues() && sttr!=null){
    			String[] attrvalues = sttr.split(",");
    			String[] values = tn.getAttributeValues().split(",");
    			for(int i=0;i<values.length;i++){
    				String sttrValue = values[i];
    				str = str + TreeNodeViewUtil.treeUtilProperties.getProperty(attrvalues[i]+"."+sttrValue,sttrValue);
    			}
    		}
    		if(tn.getNodeDesc()!=null){
    			tn.setNodeDesc(tn.getNodeDesc()+str);//描述加上属性的映射值
    		}else{
    			tn.setNodeDesc(str);
    		}
    	}
    	
    	//根目录的几个子节点需要把统计值显示出来,占比由于取不到总数，不进行显示：
    	List<TreeNodeView> childrenNodeList = root.getChildren();
    	if(childrenNodeList!=null&&childrenNodeList.size()>0){
    		for(TreeNodeView treeNode : childrenNodeList){
    			if("N".equals(treeNode.getShowValueFlag())){
    				continue;
    			}
    			List<CommonStatisticsResult> cCountList = new ArrayList<CommonStatisticsResult>();
    			CommonStatisticsSqlVO tssvo = TreeNodeViewUtil.initConditionCommonFS(treeNode,beginDate,endDate,"flow_statistics");
    			cCountList = messageService.QueryCommonFS(tssvo);
    	    	Double singleCount = Double.valueOf(0);
    	    	if(cCountList.size()>0 ){
    	    		singleCount = cCountList.get(0).getSumAmount();
    	    	}
        		treeNode.setCountValue(TreeNodeViewUtil.doubleToString(singleCount, "0", false));
    		}
    	}
    	returnMap.put("tree", root);
    	return returnMap;
    }
    
    /**
     * 
    * @Title: QueryNodeDatabyNode 
    * @Description: 查询树节点的流量包数据
    * @param @param nodeId,beginDate,endDate
    * @return Map    返回类型 
    * @throws
     */
    @RequestMapping("QueryNodeDatabyNode")
    @ResponseBody
    public Map QueryNodeDatabyNode(@RequestParam("nodeId") String nodeId,@RequestParam("beginDate") String beginDate,@RequestParam("endDate") String endDate) throws Exception{
    	//得到当前节点的信息
    	TreeNodeView treeNodeView = TreeNodeViewUtil.getTreeNodeViewByIdFromCache(nodeId);
    	
    	/*/分别查询三张表，组成流量包：设备平台、网络类型、省份地域
    	List<DeviceStatisticsResult> deviceCountList = new ArrayList<DeviceStatisticsResult>();
    	DeviceStatisticsSqlVO dssvo = TreeNodeViewUtil.initConditionDeviceFS(treeNodeView,beginDate,endDate);
    	deviceCountList = messageService.QueryDeviceFS(dssvo);
    	for(DeviceStatisticsResult dsr : deviceCountList){
    		dsr.setNamedesc(TreeNodeViewUtil.properties.getProperty(dsr.getPlatformCode()));
    	}
    	
    	List<NettypeStatisticsResult> netCountList = new ArrayList<NettypeStatisticsResult>();
    	NettypeStatisticsSqlVO nssvo = TreeNodeViewUtil.initConditionNettypeFS(treeNodeView,beginDate,endDate);
    	netCountList = messageService.QueryNettypeFS(nssvo);
    	for(NettypeStatisticsResult dsr : netCountList){
    		dsr.setNamedesc(TreeNodeViewUtil.properties.getProperty(dsr.getOperatorCode(),dsr.getOperatorCode()));
    	}
    	
    	List<RegionStatisticsResult> regionCountList = new ArrayList<RegionStatisticsResult>();
    	RegionStatisticsSqlVO rssvo = TreeNodeViewUtil.initConditionRegionFS(treeNodeView,beginDate,endDate);
    	rssvo.setChannelCode(Arrays.asList("2d44"));
    	regionCountList = messageService.QueryRegionFS(rssvo);
    	for(RegionStatisticsResult dsr : regionCountList){
    		dsr.setNamedesc(dsr.getRegionCode());
    	}*/
    	
    	//根据传入的参数，查询相应的结果集
    	List<CommonStatisticsResult> deviceCountList = new ArrayList<CommonStatisticsResult>();
    	CommonStatisticsSqlVO dssvo = TreeNodeViewUtil.initConditionCommonFS(treeNodeView,beginDate,endDate,"DeviceCount");
    	deviceCountList = messageService.QueryCommonFS(dssvo);
    	
    	List<CommonStatisticsResult> netCountList = new ArrayList<CommonStatisticsResult>();
    	CommonStatisticsSqlVO nssvo = TreeNodeViewUtil.initConditionCommonFS(treeNodeView,beginDate,endDate,"NetTypeCount");
    	netCountList = messageService.QueryCommonFS(nssvo);
    	
    	List<CommonStatisticsResult> regionCountList = new ArrayList<CommonStatisticsResult>();
    	CommonStatisticsSqlVO rssvo = TreeNodeViewUtil.initConditionCommonFS(treeNodeView,beginDate,endDate,"RegionCount");
    	regionCountList = messageService.QueryCommonFS(rssvo);
    	
    	//处理流量包中的数据，列表数量及合计.
    	Map deviceCountInfo = TreeNodeViewUtil.handleResultListInfo("deviceCountInfo","10",deviceCountList);
    	
    	Map netCountInfo = TreeNodeViewUtil.handleResultListInfo("netCountInfo","10",netCountList);
    	List<CommonStatisticsResult> netCountList2 = new ArrayList<CommonStatisticsResult>();//过滤不正确的网络运营商
    	for(CommonStatisticsResult comSR : netCountList){
    		if("NONE".equals(comSR.getCommonCode())||"CM".equals(comSR.getCommonCode())||"CT".equals(comSR.getCommonCode())||"CU".equals(comSR.getCommonCode())){
    			netCountList2.add(comSR);
    		}
    	}
    	
    	Map regionCountInfo = TreeNodeViewUtil.handleResultListInfo("regionCountInfo","10",regionCountList);//城市显示十条最多的
    	
    	Map map = new HashMap();
    	//添加设备平台统计数据
    	map.put("deviceCount", deviceCountList);
    	map.put("deviceCountInfo", deviceCountInfo);
    	map.put("netCount", netCountList2);
    	map.put("netCountInfo", netCountInfo);
    	map.put("regionCount", regionCountList);
    	map.put("regionCountInfo", regionCountInfo);
    	return map;
    }
    
    /**
     * 
    * @Title: QueryChildrenRateAndCount 
    * @Description: 查询树节点的数量和占比
    * @param @param nodeId,beginDate,endDate
    * @return TreeNodeView    返回类型 
    * @throws
     */
    @RequestMapping("QueryChildrenRateAndCount")
    @ResponseBody
    public TreeNodeView QueryChildrenRateAndCount(@RequestParam("nodeId") String nodeId,@RequestParam("beginDate") String beginDate,@RequestParam("endDate") String endDate){
    	//得到当前节点的信息及其子节点的列表
    	TreeNodeView treeNodeView = TreeNodeViewUtil.getTreeNodeViewByIdFromCache(nodeId);
    	List<TreeNodeView> childrenNodeList = TreeNodeViewUtil.getChildrenTreeNodeListByParentIdFromCache(nodeId);
    	
    	//根据此节点查询流量数量totalcount，
    	List<CommonStatisticsResult> deviceCountList = new ArrayList<CommonStatisticsResult>();
    	CommonStatisticsSqlVO dssvo = TreeNodeViewUtil.initConditionCommonFS(treeNodeView,beginDate,endDate,"flow_statistics");
    	deviceCountList = messageService.QueryCommonFS(dssvo);
    	Double totalcount = Double.valueOf(0);
    	if(deviceCountList.size()>0 ){
    		totalcount = deviceCountList.get(0).getSumAmount();
    	}
    	
    	//循环遍历子节点列表，查询转化率表，得到统计数量，算出百分占比
    	//注意一些特殊的节点，如：虚拟节点等
    	if(childrenNodeList!=null&&childrenNodeList.size()>0){
    		for(TreeNodeView treeNode : childrenNodeList){
    			List<CommonStatisticsResult> cCountList = new ArrayList<CommonStatisticsResult>();
    			CommonStatisticsSqlVO tssvo = TreeNodeViewUtil.initConditionCommonFS(treeNode,beginDate,endDate,"flow_statistics");
    			cCountList = messageService.QueryCommonFS(tssvo);
    	    	Double singleCount = Double.valueOf(0);
    	    	if(cCountList.size()>0 ){
    	    		singleCount = cCountList.get(0).getSumAmount();
    	    	}
    	    	if(singleCount.compareTo(Double.valueOf(0))>0){
    	    		double dou = totalcount.compareTo(Double.valueOf(0)) > 0 ? singleCount/totalcount : 0;
    	    		treeNode.setRateValue(TreeNodeViewUtil.doubleToString(dou, "2", true));
        			treeNode.setCountValue(TreeNodeViewUtil.doubleToString(singleCount, "0", false));
    	    	}else{
    	    		treeNode.setRateValue(TreeNodeViewUtil.doubleToString(Double.valueOf(0), "2", true));
    	    		treeNode.setCountValue(TreeNodeViewUtil.doubleToString(singleCount, "0", false));
    	    	}
    		}
    		treeNodeView.setChildren(childrenNodeList);
    		return treeNodeView;
    	}
    	/*if(childrenNodeList!=null&&childrenNodeList.size()>0){
    		for(TreeNodeView treeNode : childrenNodeList){
    			//根据此节点查询统计数据，表flow_statistics_conversion
    			StatisticsSqlVO ssVO = TreeNodeViewUtil.initConditionFSConversion(treeNode,beginDate,endDate);
    			List<FlowStatisticsResult> fsrList = messageService.QueryFSConversion(ssVO);
    			//设置此节点的rateValue和countValue
    			Double rate = Double.valueOf(0);
    			Double count = Double.valueOf(0);
    			for(FlowStatisticsResult fsr : fsrList){
    				count = count + fsr.getSumAmount();
    			}
    			treeNode.setRateValue(TreeNodeViewUtil.doubleToString(rate, "2", true));
    			treeNode.setCountValue(TreeNodeViewUtil.doubleToString(count, "0", false));
    		}
    		TreeNodeView[] children = new TreeNodeView[childrenNodeList.size()];
    		for(int i = 0;i<childrenNodeList.size();i++){
    			children[i] = childrenNodeList.get(i);
    		}
    		treeNodeView.setChildren(children);
    		return treeNodeView;
    	}*/
    	return treeNodeView;
    }
    
    /**
     * 
    * @Title: isAddNodeList 
    * @Description: 暂时保留此方法，为了以后动态增加节点
    * @param @param nodeId
    * @return List    返回类型 
    * @throws
     */
    @RequestMapping("isAddNodeList")
    @ResponseBody
    public List isAddNodeList(@RequestParam("nodeId") String nodeId){
    	List<TreeNodeView> nodeList = messageService.QueryAllTreeNodeView();
    	TreeNodeView parentNode = TreeNodeViewUtil.getTreeNodeViewById(nodeId, nodeList);
    	List<CodeNode> codeNodeList = messageService.QueryAllCodeNode();
    	TreeNodeViewUtil.refreshCodeList(codeNodeList);
    	//通过TreeNodeView的信息找出所有符合此节点增加的code列表
    	//类型：渠道》设备》页面
    	//类型级别:C0>C1>C2>C3
    	//父子关系的结构
    	String codeType = parentNode.getCodeType();
    	
    	List resultList = new ArrayList();
    	for(String ct : TreeNodeViewUtil.getCodeTypeList(codeType)){
    		if(ct.equals(codeType)){
    			//取此父节点下面的所有子节点
        		Map<String, List<?>>  map = new HashMap();
        		CodeNode codeNode = TreeNodeViewUtil.getCodeNodeById(parentNode.getCodeId(), codeNodeList);
        		List<CodeNode> list = TreeNodeViewUtil.getAllChildrenCodeNode(codeNode,codeNodeList);
        		if(list != null && list.size()>0){
        			map.put(ct, list);
            		resultList.add(map);
        		}
        		if(codeType.equals("Page")&&!codeNode.getCodetypelevel().equals("P1")){
        			//专题页及其专题一等都可以跟详情页》下单页
        			List<CodeNode> listPage = TreeNodeViewUtil.getPageLevelChildrenByLevel(codeNode.getCode().startsWith("3z")?"3z":codeNode.getCode());
        			if(listPage != null && listPage.size()>0){
        				map.put(ct, listPage);
                		resultList.add(map);
        			}
        		}
    		}else{
    			//不同的CodeType取全部的节点
    			Map<String, List<?>>  map = new HashMap();
    			List<CodeNode> list = TreeNodeViewUtil.getAllChildrenCodeNodeByCodeType(ct,codeNodeList);
    			List<CodeNode> list2 = new ArrayList();
    			if(!codeType.equals("Root")){
    				for(CodeNode cn : list){
    					if(cn.getParentId() != null){
    						list2.add(cn);
    					}
    				}
    	    	}else{
    	    		list2 = list;
    	    	}
    			if(list2 != null && list2.size()>0){
    				map.put(ct, list2);
    				resultList.add(map);
    			}
    		}
    	}
    	return resultList;
    }
    
    /**
     * 
    * @Title: AddOrDelNode 
    * @Description: 暂时保留此方法，为了以后动态编辑节点
    * @param @param parentNodeId ,codeId ,type
    * @return String    返回类型 
    * @throws
     */
    @RequiresPermissions("sys:message:view")
    @RequestMapping("AddOrDelNode")
    @ResponseBody
    public String AddOrDelNode(@RequestParam("parentNodeId") String parentNodeId,
    		@RequestParam("codeId") String codeId,@RequestParam("type") String type) throws Exception {
    	//增加树节点\删除树节点
    	if("add".equals(type)){
    		//增加规则注意：
    		//根节点下面的分支必须有前缀(这条可以不要，只是增加数据的可读性而已)
    		//同一个父节点下面只能有一个同样类型的子节点(前端下拉框过滤掉)
    		List<CodeNode> codeNodeList = messageService.QueryAllCodeNode();
    		CodeNode cn = TreeNodeViewUtil.getCodeNodeById(codeId, codeNodeList);
    		
    		List<TreeNodeView> treeNodeList = messageService.QueryAllTreeNodeView();
    		String parentDepth = TreeNodeViewUtil.getTreeNodeViewById(parentNodeId, treeNodeList).getNodeDepth();
    		String childrenDepth;
    		if(parentDepth == null || "".equals(parentDepth)){
    			childrenDepth = "";
    		}else{
    			childrenDepth = (Integer.parseInt(parentDepth) + 1) + "";
    		}
    		TreeNodeView treeNodeView = new TreeNodeView();
    		Random random = new Random();
    		treeNodeView.setNodeId("qq125486652"+random.nextInt(1000));//先这样处理，之后改成自动增加的序列
    		treeNodeView.setNodeName(cn.getName());
    		treeNodeView.setNodeDesc(cn.getName());
    		treeNodeView.setNodeParentId(parentNodeId);
    		treeNodeView.setShowValueFlag("Y");
    		treeNodeView.setCodeType(cn.getCodetype());
    		treeNodeView.setCodeId(codeId);
    		treeNodeView.setCodeValue(cn.getCode());
    		treeNodeView.setNodeDepth(childrenDepth);
    		treeNodeView.setNodeIsEdit("Y");
    		messageService.insertTreeNodeView(treeNodeView);
    		return "wsh/EditStatisticsTree";
    	}else{
    		TreeNodeView treeNodeView = new TreeNodeView();
    		treeNodeView.setNodeId(parentNodeId);
    		messageService.deleteTreeNodeView(treeNodeView);
    		return "wsh/EditStatisticsTree";
    	}
    }
}
